package com.daydr3am.lib;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.coe3.data.Information;
import com.daydr3am.thenation.Content;
import com.daydr3am.thenation.DontMiss;
import com.daydr3am.thenation.Hilight;
import com.daydr3am.thenation.R;
import com.daydr3am.thenation.TheNationMain;
import com.daydr3am.thenation.Vdo_View;
import com.squareup.picasso.Picasso;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CustomView extends RelativeLayout{
	public int index;
	NodeList list;
	NodeList nl_vdo;
	public int index_random;
	public static String url_vdo;
	

	public CustomView(Context context) {
		super(context);
	}
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

	public void onShowView() {
		//<===================================   Hilight   ===================================>
		
		Hilight hilight= (Hilight) findViewById(R.id.mainlayout_hilightScrollview);
		if(index==0)
			hilight.hilight=true;
		
		String[] urls = null;
		
		if(TheNationMain.getIsOffline(getContext())){
			urls = getResources().getStringArray(R.array.url_offline_top);
		} else {
			if(Information.isOnline(getContext())){
				urls = getResources().getStringArray(R.array.url_top);
			}//end if
		}//end if
		
		hilight.url=urls[index];
		hilight.onShowView();
		
		//<===================================   Content   ===================================>

		Content content= (Content) findViewById(R.id.mainlayout_contentscrollview);
		if(index==0)
			content.hilight=true;
		
//		urls = getResources().getStringArray(R.array.url_feed);
		
		if(TheNationMain.getIsOffline(getContext())){
			urls = getResources().getStringArray(R.array.url_offline_feed);
		} else {
			if(Information.isOnline(getContext())){
				urls = getResources().getStringArray(R.array.url_feed);
			}//end if
		}//end if
		
		content.url=urls[index];
		content.onShowView();
		
		//<===================================   TouchyWebView   ===================================>

		TouchyWebView web=(TouchyWebView) findViewById(R.id.mainlayout_webview);
		
		if(TheNationMain.getIsOffline(getContext())){
			String url = "file://" + TheNationMain.getPathCurrentNew(getContext());
			web.url = url + "/Section-Page.html";
		} else {
			if(Information.isOnline(getContext())) {
				int section=TheNationMain.getSectionFromPage(index, getContext())+1;
				web.url="http://www.nationmultimedia.com/new/rss/ipad_v2/banner/NT_Sidebannen"+section+".htm";
			}//end if
		}//end if
		
		web.onShowView();
    	web.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
    	
    	//<===================================   DontMiss   ===================================>

		DontMiss dont= (DontMiss) findViewById(R.id.mainlayout_dontmiss);
//		urls = getResources().getStringArray(R.array.dont_miss);
		
		if(TheNationMain.getIsOffline(getContext())){
			urls = getResources().getStringArray(R.array.dont_miss_offline);
		} else {
			if(Information.isOnline(getContext())){
				urls = getResources().getStringArray(R.array.dont_miss);
			}//end if
		}//end if
		
		dont.url=urls[index];
		dont.onShowView();
		
		//<===================================   LongOperation   ===================================>
		
		if(TheNationMain.getIsOffline(getContext())){
			findViewById(R.id.viedoDetail).setVisibility(View.INVISIBLE);
		} else {
			if(Information.isOnline(getContext())){
				LongOperation operate=new LongOperation();
				operate.execute("");
			}//end if
		}//end if
	}
    public void receiveData(){
		RelativeLayout group=(RelativeLayout) findViewById(R.id.viedoDetail);
		
		TextView title=(TextView) group.findViewById(R.id.video_title_textview);
		ImageView thumb=(ImageView) group.findViewById(R.id.video_thumb_image);
		ImageLoader loader=new ImageLoader(getContext());
		
		Random r=new Random();
		//int index=(r.nextInt(list.getLength()/2));
		index_random=(r.nextInt(list.getLength()/2));
		Log.v("hello", "random "+index_random);
		
		Node node=list.item(index_random*2+1);			//index 1,5, 
		if(node.getChildNodes().item(1)==null)
			return;
	
		title.setText( node.getChildNodes().item(1).getTextContent());
		
		//xxx
//		loader.DisplayImage(node.getChildNodes().item(5).getAttributes().getNamedItem("url").getTextContent(), 0, thumb);
		
		if(TheNationMain.getIsOffline(getContext())){
			File path = new File(TheNationMain.getPathCurrentNew(getContext()), node.getChildNodes().item(5).getAttributes().getNamedItem("url").getTextContent());
			if(!path.exists())
				path = new File(TheNationMain.getPathCurrentNew(getContext()), "default.gif");
				
//			Bitmap mBitmap = null;
//			mBitmap = BitmapFactory.decodeFile(path.getAbsolutePath());
//			thumb.setImageBitmap(mBitmap);
			
			Picasso.with(getContext())
			  .load(new File(path.getAbsolutePath()))
			  .error(R.drawable.ic_empty)
			  .into(thumb);
		} else {
			if(Information.isOnline(getContext())){
	    		loader.DisplayImage(node.getChildNodes().item(5).getAttributes().getNamedItem("url").getTextContent(), 0, thumb);
			}//end if
		}//end if
		
		url_vdo = nl_vdo.item(index_random).getFirstChild().getNodeValue();
		
		//------------ click vdo for view vdo ---------------
		group.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent goVDOview = new Intent(getContext(), Vdo_View.class);
				getContext().startActivity(goVDOview);
			}
		});
    }
    
    
    
    private class LongOperation extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			publishProgress();
			try {
				HttpGet uri = new HttpGet("http://www.nationmultimedia.com/new/rss/ipad_v2/ipad_vdo.xml");    

				DefaultHttpClient client = new DefaultHttpClient();
				HttpResponse resp = client.execute(uri);

				StatusLine status = resp.getStatusLine();
				if (status.getStatusCode()!=200) {
				    Log.d("hello", "HTTP error, invalid server status code: " + resp.getStatusLine());  
				}

				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(resp.getEntity().getContent());
				list=doc.getChildNodes().item(0).getChildNodes();
				nl_vdo = doc.getElementsByTagName("video");
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			return "Executed";
		}

		@Override
		protected void onPostExecute(String result) {
			receiveData();
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
}
